import 'dart:async';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_base/http/http_export.dart';
import 'package:flutter_base/user/app_user_manager.dart';
import 'package:flutter_base/utils/log/utils_log.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:get/get.dart';
import 'package:flutter_base/utils/permisson/permission_utils.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';

class ImagePickerUtils {
  ImagePickerUtils._(); // 私有构造函数

  static Future<List<AssetEntity>?> picker(
    int maxAssetsCount,
    List<AssetEntity>? selectedAssets,
  ) async {
    if (!(await PermissionUtils.checkPermission(Permission.photos))) {
      return null;
    }
    return AssetPicker.pickAssets(
      Get.context!,
      pickerConfig: AssetPickerConfig(
        maxAssets: maxAssetsCount,
        selectedAssets: selectedAssets,
        specialPickerType: SpecialPickerType.noPreview,
        requestType: RequestType.image,
        filterOptions: FilterOptionGroup(
          videoOption: const FilterOption(
            durationConstraint: DurationConstraint(
              max: Duration(minutes: 1),
            ),
          ),
        ),
        selectPredicate: (BuildContext c, AssetEntity a, bool isSelected) {
          debugPrint('Asset title: ${a.title}');
          return a.title?.endsWith('.gif') != true;
        },
      ),
    );
  }

  // static Future<AssetEntity?> pickerAndEdit() async {
  //   List<AssetEntity>? images = await picker(1, null);
  //   if (images?.isNotEmpty == true) {
  //     return ImagePickerUtils.cropImage(images!.first);
  //   } else {
  //     return null;
  //   }
  // }

  static Future<AssetEntity?> camera() async {
    if (!(await PermissionUtils.checkPermission(Permission.camera))) {
      return null;
    }

    //降低在某些手机（moto）上申请动态权限后立刻打开相机导致相机黑屏的概率
    await Future.delayed(const Duration(milliseconds: 500));

    final AssetEntity? entity = await CameraPicker.pickFromCamera(
      Get.context!,
      pickerConfig: CameraPickerConfig(
        enableRecording: false,
        imageFormatGroup: ImageFormatGroup.jpeg,
        textDelegate: MyCameraPickerTextDelegate(),
      ),
      locale: Get.locale,
    );

    return entity;
  }

  // static Future<AssetEntity?> cropImage(AssetEntity image) async {
  //   final imageFile = await image.file;
  //   if (imageFile == null) {
  //     clog('cropImage: imageFile = null');
  //     return null;
  //   }
  //
  //   final page = ImageEditorPage(imageFile: imageFile);
  //   AssetEntity? data = await Get.to(page);
  //   clog('cropImage finish AssetEntity: ${data?.id}');
  //   return data;
  // }

  /// Save network image to the photo library.
  static Future<bool> saveNetworkImageToPhoto(String url,
      {bool useCache = true}) async {
    if (GetPlatform.isWeb) {
      return false;
    }
    final String title = '${DateTime.now().millisecondsSinceEpoch}.jpg';
    final Uint8List? data = await getNetworkImageData(url, useCache: useCache);
    final AssetEntity? imageEntity = await PhotoManager.editor.saveImage(
      data!,
      title: title,
      filename: title,
    );
    return imageEntity != null;
  }

  /// get network image data from cached
  static Future<Uint8List?> getNetworkImageData(
    String url, {
    bool useCache = true,
    StreamController<ImageChunkEvent>? chunkEvents,
  }) async {
    return ExtendedNetworkImageProvider(url, cache: useCache)
        .getNetworkImageData(
      chunkEvents: chunkEvents,
    );
  }

  static Future<HttpResponse> uploadFileData({
    // Uint8List? fileData,
    required String filePath,
    Function(String key)? success,
    Function(dynamic error)? failure,
    Function(double)? progress,
  }) async {
    Uint8List fileData = await FlutterImageCompress.compressWithList(
      File(filePath).readAsBytesSync(),
      format: CompressFormat.jpeg,
    );

    HttpResponse response = await HttpManager().upload(
        url: API.uploadUserPhoto,
        fileData: fileData,

        filename:
            '${AppUserManager().uid}_${DateTime.now().microsecondsSinceEpoch}',
        onSendProgress: (current, total) {
          clog(
              'pManager().uploa   $current   $total  ${(current / total * 100).toStringAsFixed(2)}%');
          progress?.call(current / total);
        });

    //
    // if (response.code != null && response.code != 200) {
    //   failure?.call("文件上传失败：${response.code}  ${response.message}");
    // }
    return response;
  }
}

class MyCameraPickerTextDelegate extends CameraPickerTextDelegate {
  MyCameraPickerTextDelegate();
//
// @override
// String get languageCode => Get.locale.toString();
}
